package com.yuyou.fn.common.util;

/**
 * Created by Administrator on 2017/12/11.
 */

import org.apache.commons.mail.*;

import java.net.URL;
import java.util.List;

/**
 * @author liny
 *    邮件发送工具类
 */
public class EmailUtil {


    public static void sendMail(String userName,String passWord,String smtpAddress,int smtpPortSSl,String from,String toAddress, String subject, String content,List<String> urls, List<String> names){
        ImageHtmlEmail email = new ImageHtmlEmail();
        email.setHostName(smtpAddress);
        email.setSmtpPort(smtpPortSSl);
        email.setAuthenticator(new DefaultAuthenticator(userName, passWord));
        //email.setSSLOnConnect(true);
        email.setSSLOnConnect(true);//commons-mail-1.1支持的方法，1.4中使用setSSLOnConnect(true)代替
       // email.setAuthentication("284046433@qq.com","jmnbctvdviqgbjae");
        try {
            email.setFrom(from);
            email.setSubject(subject);
            email.setMsg(content);
            email.addTo(toAddress);

            if(urls != null && names != null ){
                addAttachment(email,urls,names);
            }

            email.send();

        } catch (EmailException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        //test
        String subject = "测试邮件";
        String content = "test test test。。。测试内容。。。这是从MailUtil.java发来的。";
        String to = "2410412576@qq.com";
       // EmailUtil.sendMail(_USER_NAME_,_PASSWORD_,_SMTP_ADDRESS_,_SMTP_PORT_SSL_,from,to, subject, content,Arrays.asList("http://www.aisinogz.com:19876/AisinoFp-test/pd?id=939072286783873024_144000930000_10707196.pdf"),Arrays.asList("test.pdf"));
    }
    /**
     * 为邮件添加附件
     * @param email 邮件
     * @param urls 附件链接
     * @param names 附件名称,最好有后缀名才能预览文件
     */
    public static void addAttachment(HtmlEmail email, List<String> urls, List<String> names) {
        // 保证附件名的长度和链接一一对应
        while(urls.size() > names.size()) {
            names.add("");
        }

        for(int i = 0; i < urls.size(); i++) {
            EmailAttachment attachment = new EmailAttachment();
            try {
                attachment.setURL(new URL(urls.get(i)));
                attachment.setDisposition(EmailAttachment.ATTACHMENT);
//				attachment.setDescription("Apache logo");
                attachment.setName(names.get(i));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                email.attach(attachment); // 将附件添加到邮件中
            } catch (EmailException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }



}